package org.example.cat.demo.gateway.web;

import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Transaction;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 *
 * @author ld
 * @date 2022/3/27
 */
@RestController
public class GatewayController {
    @Resource
    private RestTemplate restTemplate;

    /**
     * 指向订单服务的接口
     */
    @Value("${order.address:localhost:8082}")
    private String orderAddress;

    /**
     * 模拟正常的请求
     * @return
     * @throws Exception
     */
    @RequestMapping("/gateway")
    public String gateway() throws Exception {
        Thread.sleep(100);
        String response = restTemplate.getForObject("http://" + orderAddress + "/order", String.class);
        return "gateway response ==> " + response;
    }

    /**
     * 模拟一个请求异常
     * @return
     * @throws Exception
     */
    @RequestMapping("/timeout")
    public String timeout() throws Exception {
        Transaction t = Cat.newTransaction(CatConstants.TYPE_URL, "timeout");
        try {
            Thread.sleep(100);
            return restTemplate.getForObject("http://" + orderAddress + "/timeout", String.class);
        }catch(Exception e) {
            Cat.getProducer().logError(e);
            t.setStatus(e);
            throw e;
        }finally {
            t.complete();
        }
    }
}
